import SwiftUI

struct SmallWin: View {
    @Binding var showFloatingWindow: Bool
    @StateObject private var viewModel = MainPicaViewModel()
    
    // 使用 GeometryReader 替代直接访问 UIScreen.main.bounds
    @State private var position: CGPoint = .zero
    @State private var dragStartPosition: CGPoint?
    
    // 动画相关状态
    @State private var scaleEffect: CGFloat = 0
    @State private var animateUp = true
    @State private var selectitem: MainPica = mainpicas[0]
    @State private var isReady = false
    
    // 常量提取
    private let windowSize = CGSize(width: 90, height: 120)
    private let animationDuration = 1.0
    private let shadowRadius: CGFloat = 8
    
    var body: some View {
        GeometryReader { geometry in
            VStack {
                Spacer()
                HStack {
                    Spacer()
                    if isReady {
                        floatingWindowView
                            .position(position)
                            .scaleEffect(scaleEffect)
                            .gesture(dragGesture(for: geometry.size))
                            .onAppear {
                                initialPosition(in: geometry.size)
                                startBreathingAnimation()
                            }
                    }
                }
                .padding()
                .transition(.move(edge: .bottom))
            }
        }
        .onAppear {
            loadInitialData()
        }
        .animation(.easeInOut, value: showFloatingWindow)
    }
    
    // MARK: - Subviews
    private var floatingWindowView: some View {
        ZStack(alignment: .topTrailing) {
            RoundedRectangle(cornerRadius: 8)
                .fill(Color("BgColor2"))
                .frame(width: windowSize.width, height: windowSize.height)
                .shadow(color: .black, radius: shadowRadius, x: 2, y: 2)
            
            VStack {
                // 根据video_type判断显示图片还是视频播放器
                if selectitem.type == 1 || selectitem.type == 2 {
                    // 视频内容使用播放器
                    // KSVideoPlayerWrapper(
                    //     videoURL: selectitem.url,
                    //     videoType: selectitem.video_type,
                    //     videoId: String(selectitem.id),
                    //     shouldAutoPlay: true, // 悬浮窗中自动播放
                    //     isMuted: true // 悬浮窗中静音播放
                    // )
                    DetailVideoPlayer(
                        videoURL: selectitem.url,
                        videoId: String(selectitem.id),
                        shouldFillScreen: false,  // 不使用铺满模式
                        videoType: 1  // 视频类型为0，使用默认模式
                    )
                    .frame(width: windowSize.width, height: 90)
                    .clipShape(
                        UnevenRoundedRectangle(
                            topLeadingRadius: 8,
                            bottomLeadingRadius: 0,
                            bottomTrailingRadius: 0,
                            topTrailingRadius: 8
                        )
                    )
                    .onAppear {
                        // 通知播放管理器开始播放这个视频
                        VideoPlaybackManager.shared.startPlaying(videoId: String(selectitem.id))
                    }
                    .onDisappear {
                        // 当悬浮窗消失时停止播放
                        VideoPlaybackManager.shared.stopCurrentVideo()
                    }
                } else {
                    // 非视频内容使用图片
                    CachedImageView(imageURL: selectitem.cover)
                        .scaledToFill()
                        .frame(width: windowSize.width, height: 90)
                        .clipShape(
                            UnevenRoundedRectangle(
                                topLeadingRadius: 8,
                                bottomLeadingRadius: 0,
                                bottomTrailingRadius: 0,
                                topTrailingRadius: 8
                            )
                        )
                }
                
                NavigationLink {
                    DetailView(item: selectitem)
                } label: {
                    Text("继续观看")
                        .foregroundColor(.gray)
                        .font(.system(size: 14, weight: .medium))
                }
                
                Spacer()
            }
            .frame(width: windowSize.width, height: windowSize.height)
            
            closeButton
        }
    }
    
    private var closeButton: some View {
        Button {
            showFloatingWindow = false
        } label: {
            Image(systemName: "xmark")
                .font(.system(size: 13, weight: .bold))
                .foregroundStyle(.white)
                .padding(4)
                .background(.ultraThinMaterial)
                .clipShape(Circle())
        }
        .offset(x: -2, y: 2)
    }
    
    // MARK: - Gestures
    private func dragGesture(for screenSize: CGSize) -> some Gesture {
        DragGesture()
            .onChanged { gesture in
                if dragStartPosition == nil {
                    dragStartPosition = position
                }
                
                let newX = dragStartPosition!.x + gesture.translation.width
                let newY = dragStartPosition!.y + gesture.translation.height
                
                withAnimation(.easeInOut(duration: 0.2)) {
                    position.x = min(max(newX, 25), screenSize.width + 5 - windowSize.width)
                    position.y = min(max(newY, 50), screenSize.height - 50 - windowSize.height)
                }
            }
            .onEnded { _ in
                withAnimation(.easeOut(duration: 0.3)) {
                    // 贴边效果
                    let screenWidth = screenSize.width
                    if position.x < screenWidth / 2 {
                        position.x = 35  // 吸附到左边
                    } else {
                        position.x = screenWidth + 5 - windowSize.width  // 吸附到右边
                    }
                }
                dragStartPosition = nil
            }
    }
    
    // MARK: - Methods
    private func initialPosition(in screenSize: CGSize) {
        position = CGPoint(
            x: screenSize.width - 80,
            y: screenSize.height / 2 - 65
        )
    }
    
    private func loadInitialData() {
        viewModel.get_last_main(page: 1, fav_type: 2) {
            if let firstItem = viewModel.homehis.first {
                selectitem = firstItem
                isReady = true
                withAnimation(.easeOut(duration: 0.5)) {
                    scaleEffect = 1.0
                }
            } else {
                selectitem = mainpicas[0]
            }
        }
    }
    
    private func startBreathingAnimation() {
        Timer.scheduledTimer(withTimeInterval: animationDuration / 2, repeats: true) { _ in
            withAnimation(.easeInOut(duration: animationDuration)) {
                scaleEffect = animateUp ? 1.05 : 1.0
                animateUp.toggle()
            }
        }
    }
}

#Preview {
    @Previewable @State var showFloatingWindow = false
    SmallWin(showFloatingWindow: $showFloatingWindow)
        .background(Color("BgColor1"))
}
